import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import com.github.sarxos.webcam.Webcam;

/**
 * CameraListener takes pictures each 100 milliseconds from a connected camera 
 * and uses the ClientListner method sendCameraMessage to send it to the Client.
 * 
 * @author Torbjorn Elebjork
 */
public class CameraListener extends Thread {
	BufferedImage image;
	VideoStreamServer videoStreamServer;
	
	/**
	 * Opens the camera it its closed and initialize the client object reference. 
	 */
	public CameraListener(VideoStreamServer videoStreamServer) {
		this.videoStreamServer = videoStreamServer;
		Webcam.setAutoOpenMode(true);
	}

	/**
	 * Takes pictures each 100 milliseconds from a connected camera 
	 * and uses the ClientListner method sendCameraMessage to send it to the Client.
	 */
	public void run() {
		while(true){
			try {
				Thread.sleep(100);
				image = Webcam.getDefault().getImage();
				videoStreamServer.sendCameraMessage(new ImageIcon(image));
			} 
			catch (IOException e) {
				System.out.println("Image could not be sent to the client.");
				e.printStackTrace();
			} 
			catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
